<template>

  <el-dialog
    top="20px"
    :title="defaultValue.title"
    :lock-scroll="tableConfig.lockScroll"
    :append-to-body="tableConfig.appendToBody"
    :visible="tableConfig.show"
    @close="tableConfig.show = false"
    :show-close="tableConfig.showClose"
    :destroy-on-close="tableConfig.destroyOnClose"
    width="1100px">

    <el-form ref="formBook" :rules="rulesShoppingCart" :model="formShoppingCart" label-width="180px">
      <el-form-item label="物品名称" prop="name" >
        <el-input v-model.trim="formShoppingCart.name"></el-input>
      </el-form-item>
      <el-form-item label="商品链接地址" prop="path" >
        <el-input v-model.trim="formShoppingCart.path">
          <template slot="prepend">url</template>
        </el-input>
      </el-form-item>
      <el-form-item label="详情" prop="details" >
        <el-input v-model.trim="formShoppingCart.details" type="textarea"></el-input>
      </el-form-item>
      <el-form-item label="商品类型" prop="typeId">
        <el-select v-model="formShoppingCart.typeId" placeholder="请选择商品类型">
          <el-option
            v-for="item in shoppingCartTypeList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="评分" prop="grade" >
        <el-rate v-model="formShoppingCart.grade" :texts="texts" show-text></el-rate>
      </el-form-item>

      <el-form-item label="买入价格" prop="price" >
        <!--只能输入数字和小数后2位-->
        <el-input v-model="formShoppingCart.price"  type="text" @keyup.native="formShoppingCart.price = onNumInput(formShoppingCart.price, 2)">
          <template slot="append">元</template>
        </el-input>
      </el-form-item>
      <el-form-item label="是否购买" prop="purchase" >
        <el-select v-model="formShoppingCart.purchase" placeholder="请选择是否购买">
          <el-option label="已购买" :value="2"></el-option>
          <el-option label="未购买" :value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="推荐理由" prop="reason" >
        <el-input v-model.trim="formShoppingCart.reason" type="textarea"></el-input>
      </el-form-item>

      <el-form-item label="图片" >
        <MultiplePictureUploadScreenshot ref="ShoppingCartImages"></MultiplePictureUploadScreenshot>
      </el-form-item>


    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button plain type="warning" @click="toSaveUpd" v-if="defaultValue.saveUpdSelect !== 'select'">{{defaultValue.title}}</el-button>
      <el-button plain type="primary" @click="tableConfig.show = false">关闭</el-button>
    </span>

  </el-dialog>

</template>

<script>

  import http from '@/utils/http'
  import {clearInvalid, getFullDate} from "../../utils/utils"
  import MultiplePictureUploadScreenshot from '../common/MultiplePictureUploadScreenshot.vue'

  export default {
    name: "ShoppingCartSaveUpd",
    components: {
      MultiplePictureUploadScreenshot
    },
    data(){
      return {
        // 表格的默认值
        tableConfig: {
          // 关闭时销毁 Dialog 中的元素
          destroyOnClose: true,
          // 弹出框是否打开
          show: false,
          // 是否显示关闭按钮
          showClose: true,
          // 下面2个属性解决打开弹出框后没有在最上面显示的问题，导致看到的内容是一半的，需要先将滚动条移到最上面
          lockScroll: false,
          appendToBody: true,
        },
        // 默认值，进入页面后的值
        defaultValue: {
          // 弹出框标题
          title: '查看',
          // 保存还是修改or查看,取值有 select | save | upd
          saveUpdSelect: 'select'
        },
        // 评价文字说明
        texts: ['非常差', '差', '普通', '优秀', '非常棒'],
        // 商品类型
        shoppingCartTypeList: [],
        // 要提交的数据
        formShoppingCart: {
          id: null,
          name: null,
          typeId: null,
          path: null,
          details: null,
          price: null,
          purchase: null,
          reason: null,
          grade: null,
        },
        // 校验规则
        rulesShoppingCart: {
          name: [{ required: true, message: '请输入物品名称', trigger: 'blur' }],
          reason: [{ required: true, message: '请输入推荐理由', trigger: 'blur' }],
          typeId: [{ required: true, message: '请选择商品类型', trigger: 'change' }],
          purchase: [{ required: true, message: '请选择是否购买商品', trigger: 'change' }],
          grade: [{ required: true, message: '请输入评分', trigger: 'blur' }],
        },
      }
    },
    methods: {
      /**
       * 限制只能数字并且只能有限长度
       * @param num 输入的数字
       * @param limit 限制的长度
       * @return {string} 清洗后的结果
       */
      onNumInput(num, limit) {
        if (!num){
          return num
        }
        var str = num
        var len1 = str.substr(0, 1)
        var len2 = str.substr(1, 1)
        // 如果第一位是0，第二位不是点，就用数字把点替换掉
        if (str.length > 1 && len1 === 0 && len2 !== '.') {
          str = str.substr(1, 1)
        }
        // 第一位不能是.
        if (len1 === '.') {
          str = ''
        }
        // 限制只能输入一个小数点
        if (str.indexOf('.') !== -1) {
          var str_ = str.substr(str.indexOf('.') + 1)
          if (str_.indexOf('.') !== -1) {
            str = str.substr(0, str.indexOf('.') + str_.indexOf('.') + 1)
          }
        }
        // 正则替换
        str = str.replace(/[^\d^.]+/g, '') // 保留数字和小数点
        if (limit / 1 === 1) {
          str = str.replace(/^\D*([0-9]\d*\.?\d{0,1})?.*$/, '$1') // 小数点后只能输 1 位
        } else {
          str = str.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/, '$1') // 小数点后只能输 2 位
        }
        return str
      },
      /**
       * 是保存还是修改书籍
       */
      toSaveUpd(){
        if (this.defaultValue.saveUpdSelect === 'save'){
          this.saveShoppingCart()

        } else if (this.defaultValue.saveUpdSelect === 'upd'){
          this.updShoppingCart()

        } else {

        }
      },
      /**
       * 保存购物信息
       */
      saveShoppingCart(){
        let formData = new FormData()
        this.appendPram(formData)
        // 获取上传的图片
        let uploadList = this.$refs.ShoppingCartImages.upload.fileList
        uploadList.forEach((file) => {
          formData.append('file', file.raw)
        });
        http.postFileForm("/shopping/saveShoppingCart", formData).then(response => {
          let res = response.data;
          if (res.status === 'error'){
            // 401是token过期跳转的
            if (res.code !== 401){
              this.$message.error(res.msg);
            }
            return
          }

          this.$message.success("保存成功");
          this.$emit('getShoppingCartListPage', null)
          // 关闭弹出框
          this.initShoppingCart()
          this.tableConfig.show = false

        }).catch(error => {
          this.$message.error(error.message);
        })
      },
      /**
       * 拼接参数
       * @formData 提交的数据
       */
      appendPram(formData){
        for (let key in this.formShoppingCart){
          if (this.formShoppingCart[key]){
            formData.append(key, this.formShoppingCart[key])
          }
        }
      },
      /**
       * 更新购物信息
       */
      updShoppingCart(){
        let formData = new FormData()
        clearInvalid(this.formShoppingCart)
        this.appendPram(formData)
        // 处理图片
        let uploadList = this.$refs.ShoppingCartImages.upload.fileList
        uploadList.forEach((file) => {
          // 更新的时候，如果没有图片不做处理，这个时候的图片是自己放进去的，但没有 file.raw 数据
          if (file.raw){
            formData.append('file', file.raw)
          }
          // 将所有的图片id传给后端，让后端去删除不在列表中的图片
          formData.append("pictureList", file.uid)
        });
        http.postFileForm("/shopping/updShoppingCart", formData).then(response => {
          let res = response.data;
          if (res.status === 'error'){
            // 401是token过期跳转的
            if (res.code !== 401){
              this.$message.error(res.msg);
            }
            return
          }

          this.$message.success("更新成功");
          this.$emit('getShoppingCartListPage', null)
          // 关闭弹出框
          this.initShoppingCart()
          this.tableConfig.show = false

        }).catch(error => {
          this.$message.error(error.message);
        })
      },
      /**
       * 打开弹出框之前
       * @param value 保存还是修改or查看,取值有 select \ save \ upd
       * @param obj 如果是修改和查看，则是详细数据,需要赋值
       * @param type 游戏类型
       */
      openShoppingCartPage(value, obj, type){
        // 从父组件传入，减少查询
        this.shoppingCartTypeList = type
        this.defaultValue.saveUpdSelect = value
        this.initShoppingCart()

        if (value === 'save'){
          this.defaultValue.title = '新增商品'

        } else if (value === 'upd'){
          this.defaultValue.title = '修改商品'
          this.formShoppingCart = JSON.parse(JSON.stringify(obj))

          // 页面加载完成后执行，否则无法获取到dom
          this.$nextTick(() => {
            if (this.formShoppingCart.uploadFileList && this.formShoppingCart.uploadFileList.length > 0){
              for (let uploadFile of this.formShoppingCart.uploadFileList){
                // 对图片进行处理，回显
                let poster = {name: uploadFile.id, url: uploadFile.savePath, uid: uploadFile.id}
                // 先清空，否则可能数据污染
                this.$refs.ShoppingCartImages.upload.fileList = []
                this.$refs.ShoppingCartImages.upload.fileList.push(poster)
                this.$refs.ShoppingCartImages.uploadHide()
              }
            }
          })

        } else {

        }

        this.tableConfig.show = true
        this.$store.commit('navigationListChange', ['我的购物', this.defaultValue.title])

      },
      /**
       * 初始化商品信息
       */
      initShoppingCart(){
        this.formShoppingCart = {
          id: null,
          name: null,
          typeId: null,
          path: null,
          details: null,
          price: null,
          purchase: null,
          reason: null,
          grade: null,
        }
      },
    },
    mounted(){

    },
  }
</script>

<style scoped>

</style>
